<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 后台控制器基类
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\BaseController;
use think\facade\View;
use app\common\model\Config;

class AdminBaseController extends BaseController
{
    /**
     * 初始化
     */
    protected function initialize()
    {
        parent::initialize();

        // 身份验证
        $this->authorization();

        // 系统配置
        $site_info = Config::config('website');
        View::assign('site_info', $site_info);
    }

    /**
     * 身份验证
     * 多应用中间件获取不到controller和action
     */
    private function authorization()
    {
        $request = $this->request;
        $allow_rule = [
            'admin/login',
            'admin/login/save'
        ];
        $app = app('http')->getName();
        $controller = $request->controller(true);
        //$controller = str_replace('.', '/', $controller); // admin.index/index => admin/index/index
        $action     = $request->action(true);
        $action     = $action == 'index' ? '' : '/' . $action;
        $route      = $app . '/' . $controller . $action;

        if (!in_array($route, $allow_rule)) {
            // 验证登录状态
            $this->user = $this->auth()->user();
            if (!$this->user) {
                $this->redirect('/admin/login');
            }
            $this->user_id = $this->user->id;
            // 验证后台权限
            if ($this->user_id != 1) {
                $result = $this->auth()->hasPermission($route, $this->user_id);
                if (!$result) {
                    return json(['code' => 10002, 'msg' => 'Forbidden'], 403);
                }
            }
        }
        return true;
    }

    /**
     * 过滤字段
     * @param string $field
     * @return array
     */
    protected function param(string $field): array
    {
        $where = [];
        if ($field) {
            $field = explode(',' , $field);
            $param = $this->request->param();
            foreach ($field as $value) {
                if (!empty($param[$value])) {
                    $where[] = [$value, '=', trim($param[$value])];
                }
            }
        }
        return $where;
    }
}